package model

import (
	"context"
	"log"
	"time"
)

type MotherDog struct {
	ctx           context.Context
	littleDogDead context.CancelFunc
}

func (self *MotherDog) Init() {
	_ctx, cancle := context.WithCancel(context.Background())
	self.ctx = _ctx
	self.littleDogDead = cancle
}

//添加一只小狗
func (self *MotherDog) Born(feedinteralSec int, name string) (litdog *littleDog) {
	litdog = new(littleDog)
	litdog.name = name
	litdog.food = make(chan int, 1)
	litdog.exit = make(chan bool, 1)
	litdog.feedIntevalSec = feedinteralSec
	litdog.dead = self.littleDogDead
	litdog.run()
	return litdog
}

//自动喂狗，当有小狗死掉的时候就停止喂狗，触发重启
func (self *MotherDog) AutoFeed(_feedintevalSec int, feedH func(), reboot func()) error {
	go func() {
		defer func() {
			log.Println("退出了喂狗线程，将会重启")
			reboot()
		}()
		for {
			select {
			case <-time.After(time.Duration(_feedintevalSec) * time.Second): //喂狗的时间要小于重启的时间
				//喂狗
				feedH()
			case <-self.ctx.Done():
				log.Println("有小狗死了,取消自动喂狗")
				return
			}
		}
	}()
	return nil
}
